package com.xdf.ecommerce.advice;

import com.xdf.ecommerce.annotation.IgnoreResponseAdvice;
import com.xdf.ecommerce.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author chanchaw
 * @create 2025-10-14 10:11
 */
@RestControllerAdvice(value = "com.xdf.ecommerce")// 只封装本项目域名下的响应结果（避免封装第三方响应结果）
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 有类、方法使用注解 @IgnoreResponseAdvice 则不进行封装，直接返回数据
        if(methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) return false;
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) return false;
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        CommonResponse<Object> res = new CommonResponse<>(0,"");
        if(o == null) return res;
        if(o instanceof CommonResponse) return o;
        res.setData(o);
        return res;
    }
}
